<?php
/**
 * BrandRepo.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-02-13 22:14:50
 * @modified    2023-02-13 22:14:50
 *
 */

namespace App\Repositories\Product;

use App\Models\Product\Brand;

class BrandRepo
{
    public static function getList()
    {
        $perPage = (int)request('limit');
        if ($perPage < 1) {
            $perPage = 1;
        }
        $builder = Brand::query();
        $name = trim(request()->get('name') ?? '');
        $status = trim(request()->get('status') ?? '');
        if ($status !== '') {
            $status = (int)$status;
            $builder->where('status', $status);
        }
        if ($name) {
            $builder->where('name', 'like', "%{$name}%");
        }
        $builder->orderByDesc('create_time');
        return $builder->paginate($perPage);
    }

    public static function fetch($id)
    {
        $brand = Brand::find($id);
        if (empty($brand)) {
            throw new \Exception('品牌不存在');
        }
        return $brand;
    }

    public static function destroy($id)
    {
        $brand = Brand::find($id);
        if (empty($brand)) {
            throw new \Exception('品牌不存在');
        }
        $brand->delete();
    }

    public static function store($id)
    {
        $data = self::requestData();
        if ($id) {
            $brand = Brand::find($id);
        } else {
            $brand = new Brand();
        }
        if (empty($brand)) {
            $brand = new Brand();
        }
        $brand->fill($data);
        $brand->saveOrFail();
        return self::fetch($brand->id);
    }

    private static function requestData(): array
    {
        $brandData = request()->getContent();
        $brandArr = json_decode($brandData, true);
        $image = $brandArr['image'] ?? '';

        $result = [];
        $result['image'] = $image;

        $name = trim($brandArr['name'] ?? '');
        if (empty($name)) {
            throw new \Exception('请输入品牌名称');
        }
        $result['name'] = $name;

        $sortOrder = $brandArr['sort_order'] ?? '';
        $sortOrder = (int)$sortOrder;
        $result['sort_order'] = $sortOrder;

        $status = $brandArr['status'] ?? '';
        if ($status !== '') {
            $status = (int)$status;
            if ($status > 0) {
                $status = 1;
            } else {
                $status = 0;
            }
            $result['status'] = $status;
        }
        return $result;
    }
}